<?php

class AuthController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    } 

    public function loginAction()
    {
        $authAdapter = $this->getAuthAdapter();
		
		if(Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('/');
		}
		
		$form = new Application_Form_AuthForm(array('action'=>'/auth/login', 'name'=>'loginFrm', 'fields'=>array('email'=>'Email','password'=>'Password')));

		if($this->getRequest()->isPost()) {
			if ($form->isValid($this->getRequest()->getPost())) {
				$formData = $this->getRequest()->getPost();

				$authAdapter->setIdentity($formData['email'])
							->setCredential($formData['password']);
				$auth = Zend_Auth::getInstance();

				$result = $auth->authenticate($authAdapter);

				switch ($result->getCode()) {
					case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
						$this->view->msg = 'Utilizatorul nu exista.';
					break;

					case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
						$this->view->msg = 'Date incorecte.';
					break;

					case Zend_Auth_Result::SUCCESS:
						if ($userInfo = $authAdapter->getResultRowObject(null, 'password')) {
							Zend_Auth::getInstance()->getStorage()->write($userInfo);
							$this->_redirect('/');
						} else {
							$this->view->msg = 'Autentificarea nu a putut fi efectuata, va rugam incercati din nou mai tarziu.';
						}
					break;

					default:
						$this->view->msg = 'Autentificarea nu a putut fi efectuata, va rugam incercati din nou mai tarziu.';
					break;
				}
			}
		}

		$this->view->form = $form;
    }

    public function logoutAction()
    {
		$this->_helper->viewRenderer->setNoRender();
        Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('/auth/login');
    }

    public function resetPasswordAction()
    {
		$form = new Application_Form_AuthForm(array('action'=>'/auth/reset-password', 'name'=>'resetPasswordFrm', 'fields'=>array('email'=>'Email')));
		$this->view->flag_display = 'display_form';

		if($this->getRequest()->isPost()) {
			if ($form->isValid($this->getRequest()->getPost())) {
				$formData = $this->getRequest()->getPost();

				$modelUser = new Application_Model_Users();
				$user = $modelUser->getUserByEmail( $formData['email'] );

				if ( $user ){
					$user['token'] = md5( $user['email'] . microtime() );
					$userId = $modelUser->updateUser( $user );

					// send email
					$this->view->link_reset = '/auth/change-password?token='.$user['token'];
					$html_mail_body = $this->view->render('auth/email-reset-password.phtml');

					$mail = new Zend_Mail();
					$mail->setBodyHtml($html_mail_body);
					$mail->addTo($user['email']);
					$mail->setSubject('PaginaFarmacistilor.ro - Resetare parola');
					$mail->send();
					$this->view->flag_display = 'check_email';
				}
				else{
					$this->view->err_msg = 'Adresa de email introdusa nu exista in baza de date';
				}
			}
		}

		$this->view->form = $form;
    }

	public function changePasswordAction()
	{
		$token = $this->getRequest()->getParam('token');

		$form = new Application_Form_AuthForm(array('action'=>'/auth/change-password?token='.$token, 'name'=>'changePasswordFrm', 'fields'=>array('password'=>'Password', 'password2'=>'Confirm Password')));

		$modelUser = new Application_Model_Users();
		$user = $modelUser->getUserByField( 'token', $token );
		
		if ( !$user ){
			$this->view->flag_display = 'error';
		}
		else{
			$this->view->flag_display = 'display_form';

			if($this->getRequest()->isPost()) {
				if ($form->isValid($this->getRequest()->getPost())) {
					$formData = $this->getRequest()->getPost();

					$user['password'] = md5( md5($formData['password']) . $user['salt'] );
					$userId = $modelUser->updateUser( $user );
					$this->view->flag_display = 'updated';
				}
			}
		}

		$this->view->form = $form;
	}
    
    private function getAuthAdapter(){
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        
        $authAdapter->setTableName('users')
                    ->setIdentityColumn('email')
                    ->setCredentialColumn('password')
                    ->setCredentialTreatment("MD5(CONCAT(MD5(?),salt)) AND status = '1'");
                    
        return $authAdapter;
    }

}

